package com.itheima.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.entity.Category;
import com.itheima.entity.Page;
import com.itheima.entity.Setmeal;
import com.itheima.exception.CustomException;
import com.itheima.mapper.CategoryMapper;
import com.itheima.mapper.DishMapper;
import com.itheima.mapper.SetmealMapper;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired(required = false)
    private CategoryMapper categoryMapper;
    @Autowired(required = false)
    private DishMapper dishMapper;
    @Autowired(required = false)
    private SetmealMapper setmealMapper;



    @Override
    public void save(Category category) {
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.save(category);
    }

    @Override
    public Page<Category> findByPage(Integer page, Integer pageSize) {
       //设置当前页和大小
        PageHelper.startPage(page,pageSize);
        //获取数据
       List<Category> categoryList= categoryMapper.findAll();
       //把数据放入pageinfo
        PageInfo<Category> pageInfo = new PageInfo<>(categoryList);
        //把pageinfo放入page
        Page<Category> pageResult = new Page<>(pageInfo.getList(), pageInfo.getTotal(), pageSize, page,pageInfo.getPages());

        return pageResult;

    }

    @Override
    public void removeById(long id) {
        categoryMapper.removeById(id);

    }

    @Override
    public void deleteById(long id) throws CustomException {
     long count=dishMapper.findDishCountById(id);
     if (count>0){
         throw  new CustomException("该类别关联了菜品，无法删除");
     }

      count=setmealMapper.findSetmealCountById(id);
     if (count>0){
         throw new CustomException("该类别关联了菜单，无法删除");
     }
     categoryMapper.deleteById(id);

    }

    @Override
    public void updateById(Category category) {

        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.updateById(category);
    }

    @Override
    public List<Category> list(Integer type) {
        return categoryMapper.list(type);

    }
}

